#!/bin/sh -e

SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"

if [ ! -d "$SCRIPT_DIR/k6-summary/.git" ]; then
    echo "❌ Schemas repository not found in $SCRIPT_DIR/k6-summary."
    echo "Please run the checkout script first:"
    echo "  $SCRIPT_DIR/checkout.sh"
    exit 1
fi

if ! command -v cog >/dev/null 2>&1; then
    echo "❌ 'cog' CLI not found"
    echo ""
    echo "Please install the binary from GitHub Releases:"
    echo "  https://github.com/grafana/cog/releases"
    echo ""
    exit 1
fi

# We use Go templates file extension convention to avoid issues with the linter,
# as `cog` templates have invalid Go syntax (i.e. templating syntax).
# But looks like `cog` expects `.go` files, so we rename them right before code-generation.
find "$SCRIPT_DIR/cog-templates/" -name "*.go.tmpl" -exec bash -c 'mv "$1" "${1%.go.tmpl}.go"' _ {} \;

# Run `cog` to generate the source code from the checked out schemas.
cog generate --config "$SCRIPT_DIR/cog.yaml"

# Then we leave the `cog` templates back to their original state.
find "$SCRIPT_DIR/cog-templates/" -name "*.go" -exec bash -c 'mv "$1" "$1.tmpl"' _ {} \;

# Move the Go files from the package directory to root (cwd)
SRC_DIR="$SCRIPT_DIR/summary"
find "$SRC_DIR" -maxdepth 1 -type f -name '*.go' ! -name '.*' -exec mv -f {} "$SCRIPT_DIR" \;
rm -rf "$SRC_DIR"

# Remote the docs generated by `cog`, as we don't want them for now.
rm -rf "$SCRIPT_DIR/docs"
